<template>
  <div class="container">
    <el-tag class="tag" :class="{ tagClick: $route.name === tab.name }" :style="{ width: tab.name === '首页' ? '62px' : '' }" ref="tag" color="white" @click="tabClick(tab)" @close="tabRemove(tab)" v-for="(tab, index) in tabsName" :key="index" :closable="tab.name !== '首页'">
      <span>{{ tab.name }}</span>
    </el-tag>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const tabsName = ref([{ name: '首页', path: '/dashboard' }])
const router = useRouter()
const route = useRoute()

// 删除标签
const tabRemove = (item) => {
  if (item.name !== '首页') {
    tabsName.value = tabsName.value.filter((data) => {
      return data.name !== item.name
    })
    // 跳转到前一个标签
    let path = tabsName.value[tabsName.value.length - 1].path
    router.push({ path })
  }
}
// 点击标签头时
const tabClick = (item) => {
  router.push(item.path)
}
// 监听路由变化
watch(
  () => route.path,
  (newValue) => {
    // 判断是否已经存在该标签
    let flag = tabsName.value.some((data) => {
      return data.name === route.name
    })
    // 如果不重复，则添加标签
    if (!flag) {
      const routeInfo = {
        name: route.name,
        path: route.path,
      }
      tabsName.value.push(routeInfo)
    }
  },
  {
    immediate: true,
  }
)
</script>

<style scoped>
/* .tag 为默认样式  .tagClick 为点击后样式*/
.tag {
  margin: 10px 0 1px 12px;
  border: #ebebeb 1px solid;
  text-align: center;
  border-radius: 7px;
  cursor: pointer;
}
.tag span {
  display: inline-block;
  position: relative;
  transition: 0.4s;
}
:v-deep(.tag:hover) {
  background-color: white !important;
}
:v-deep(.tag:active) {
  transform: scale(0.9);
}

.tagClick {
  background-color: #409eff !important;
  color: white !important;
}
:v-deep(.tagClick .el-tag__close) {
  color: white !important;
}
/*覆盖 .tag:hover 样式*/
:v-deep(.tagClick:hover) {
  opacity: 0.8;
  background-color: #409eff !important;
}
</style>
